#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>


#define PORT_NO 5001

void exitWithError(char* msg) {
	perror(msg);
	exit(1);
}

int main(int argc, char* argv[]) {
	int sockfd, newsockfd, n, cli_len;
	struct sockaddr_in serv_addr, cli_addr;
	char buf[256];

	// socket
	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		exitWithError("ERROR creating socket");
	}

	// init struct
	bzero((char *) &serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(PORT_NO);
	serv_addr.sin_addr.s_addr = INADDR_ANY;

	// bind
	if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
		exitWithError("ERROR binding");
	}

	// listen
	listen(sockfd, 5);
	cli_len = sizeof(cli_addr);
	// set the client socket

	char reply[] = "hello, server works\n";
	int reply_len = sizeof(reply);
	printf("reply_len =%d\n", reply_len);

	newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &cli_len);
	if (newsockfd < 0) {
		exitWithError("ERROR accept");
	}

	// read the client socket
	bzero(buf, 256);
	n = read(newsockfd, buf, 256);
	if (n < 0) {
		exitWithError("ERROR read");
	}
	printf("receive %s\n", buf);

	// write the client socket

	n = write(newsockfd, reply, reply_len);
	if (n < 0) {
		exitWithError("ERROR read");
	}
}
